package com.ruoyi.framework.web.service;


import com.ruoyi.common.constant.*;
import com.ruoyi.common.core.domain.GTPush;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.YxAndroidApplicationVo;
import com.ruoyi.common.core.domain.entity.YxUserAndDeviceVo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.domain.AppInfoVo;
import com.ruoyi.framework.web.domain.AppUsageInfoVo;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 微信业务实现类
 */
@Component
public class AppInfoService {

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);


    @Autowired
    private ISysUserService userService;

    @Autowired
    private IAndroidDeviceService androidDeviceService;

    @Autowired
    private IYxAndroidApplicationService yxAndroidApplicationService;

    @Autowired
    private IYxDeviceAndAppService yxDeviceAndAppService;


    @Autowired
    private IYxAppUsageRecordService yxAppUsageRecordService;

    @Autowired
    private IYxUserAndDeviceService yxUserAndDeviceService;

    @Autowired
    private IYxDeviceAndGetuiService yxDeviceAndGetuiService;

    @Autowired
    private IYxDeviceExtraInfoService yxDeviceExtraInfoService;

    public R<List<String>> upLoadAppInfo(List<AppInfoVo> appInfoList) {


        List<String> packageNames = new ArrayList<>();
        for(AppInfoVo appInfoVo : appInfoList){
            packageNames.add(appInfoVo.packageName);
        }
        List<YxAndroidApplication> yxAndroidApplicationList= yxAndroidApplicationService.selectYxAndroidApplicationByPackageNames(packageNames);

        // 结构化数据
        Map<String,YxAndroidApplication> yxAndroidApplicationMap= new HashMap<>();
        for (YxAndroidApplication yxAndroidApplication : yxAndroidApplicationList){
            yxAndroidApplicationMap.put(yxAndroidApplication.getPackageName(),yxAndroidApplication);
        }

        List<AppInfoVo> noExistApp = new ArrayList<>();
        List<String> noExistPackage = new ArrayList<>();
        for(AppInfoVo appInfoVo : appInfoList){
            if(!yxAndroidApplicationMap.containsKey(appInfoVo.packageName)){
                // 记录不存在应用。
                noExistApp.add(appInfoVo);
                noExistPackage.add(appInfoVo.packageName);
            }
        }

        // 批量插入不存在应用
        if(noExistApp.size() > 0){
            List<YxAndroidApplication> needToInsert = new ArrayList<>();
            for(AppInfoVo appInfoVo : noExistApp){
                YxAndroidApplication yxAndroidApplication = new YxAndroidApplication();
                yxAndroidApplication.setAppName(appInfoVo.appName);
                yxAndroidApplication.setPackageName(appInfoVo.packageName);
                yxAndroidApplication.setCreateTime(new Date());
                needToInsert.add(yxAndroidApplication);
            }
            //执行批量插入
            yxAndroidApplicationService.insertYxAndroidApplications(needToInsert);
        }

        if(noExistPackage != null && noExistPackage.size() > 0){

            // 重新查询 刚插入的数据
            List<YxAndroidApplication> yxAndroidApplicationNewList = yxAndroidApplicationService.selectYxAndroidApplicationByPackageNames(noExistPackage);

            //重新补充 进 map数据
            for (YxAndroidApplication yxAndroidApplication : yxAndroidApplicationNewList){
                yxAndroidApplicationMap.put(yxAndroidApplication.getPackageName(),yxAndroidApplication);
            }
        }

        //获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();

        // 开始执行 设备应用绑定
        List<YxDeviceAndApp> yxDeviceAndAppList = new ArrayList<>();
        noExistPackage.clear();

        //防止重复绑定 先查询当前设备已有应用列表
        YxDeviceAndApp query = new YxDeviceAndApp();
        query.setDeviceId(user.getUserName());
        List<YxDeviceAndApp> deviceAndAppListInDb = yxDeviceAndAppService.selectYxDeviceAndAppList(query);
        Set<Long> deviceAndAppSetInDb = new HashSet<>();
        for(YxDeviceAndApp yxDeviceAndApp : deviceAndAppListInDb){
            deviceAndAppSetInDb.add(yxDeviceAndApp.getAppId());
        }

        for(AppInfoVo appInfoVo : appInfoList) {

            if(!deviceAndAppSetInDb.contains(yxAndroidApplicationMap.get(appInfoVo.packageName).getId())){
                YxDeviceAndApp yxDeviceAndApp = new YxDeviceAndApp();
                yxDeviceAndApp.setAppId(yxAndroidApplicationMap.get(appInfoVo.packageName).getId());
                yxDeviceAndApp.setDeviceId(user.getUserName());
                yxDeviceAndApp.setVersionCode(appInfoVo.versionCode);
                yxDeviceAndApp.setVersionName(appInfoVo.versionName);
                yxDeviceAndApp.setStatus(AppConstants.APP_STATUS_DISABLE);
                yxDeviceAndApp.setCreateTime(new Date());

                yxDeviceAndAppList.add(yxDeviceAndApp);
            }


            // 保存应用图标不存在数据 返回给应用侧上传
            if(TextUtils.isEmpty(yxAndroidApplicationMap.get(appInfoVo.packageName).getIcon())){
                noExistPackage.add(appInfoVo.packageName);
            }
        }
        if(yxDeviceAndAppList != null && yxDeviceAndAppList.size() > 0){
            yxDeviceAndAppService.insertYxDeviceAndApps(yxDeviceAndAppList);
        }

        return R.ok(noExistPackage);
    }

    public R<String> upLoadAppInfo(AppInfoVo appInfoVo) {

        if(TextUtils.isEmpty(appInfoVo.icon)){
            return R.fail("icon 不能为空");
        }
        if(TextUtils.isEmpty(appInfoVo.packageName)){
            return R.fail("packageName 不能为空");
        }

        YxAndroidApplication query = new YxAndroidApplication();
        query.setPackageName(appInfoVo.packageName);
        List<YxAndroidApplication> yxAndroidApplicationList= yxAndroidApplicationService.selectYxAndroidApplicationList(query);
        if(yxAndroidApplicationList != null && yxAndroidApplicationList.size() == 1){
            yxAndroidApplicationList.get(0).setIcon(appInfoVo.icon);
            yxAndroidApplicationService.updateYxAndroidApplication(yxAndroidApplicationList.get(0));
            return R.ok("更新成功");
        }
        return R.fail("更新异常");

    }



    public R<String> upLoadAppUsageInfo(List<AppUsageInfoVo> appInfoList) {


        //获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();

        if(user.getUserName() != null && user.getAccountType() == LoginConstants.USER_TYPE_DEVICE_STU
                && appInfoList != null && appInfoList.size() > 0){
            AsyncManager.me().execute(AsyncFactory.upLoadAppUsageInfoInBackThread(user.getUserName(), appInfoList));
        }

        return R.ok("上传成功");
    }

    public void upLoadAppUsageInfoInBackThread(String deviceId,List<AppUsageInfoVo> appInfoList) {


        List<YxAppUsageRecord> yxAppUsageRecordListInsert = new ArrayList<>();
        List<YxAppUsageRecord> yxAppUsageRecordListUpdate = new ArrayList<>();

        for(AppUsageInfoVo appUsageInfoVo : appInfoList){

            // 查询应用信息
            YxAndroidApplication appinfo = yxAndroidApplicationService.selectYxAndroidApplicationByPackageName(appUsageInfoVo.packageName);
            if(appinfo == null){
                continue;
            }

            // 查询数据是否已插入
            YxAppUsageRecord query = new YxAppUsageRecord();
            query.setDeviceId(deviceId);
            query.setAppId(appinfo.getId());
            query.setUsageDate(new Date(appUsageInfoVo.usageDate));
            List<YxAppUsageRecord> list = yxAppUsageRecordService.selectYxAppUsageRecordList(query);

            // 组装需要插入的数据
            YxAppUsageRecord item = new YxAppUsageRecord();

            item.setAppId(appinfo.getId());
            item.setDeviceId(deviceId);
            item.setUsageDate(new Date(appUsageInfoVo.usageDate));
            item.setLaunchCount(appUsageInfoVo.launchCount);
            item.setUsageTime(appUsageInfoVo.usageTime);
            item.setCreateTime(new Date());

            // 将数据进行分类
            if(list != null && list.size() > 0){
                item.setId(list.get(0).getId());
                yxAppUsageRecordListUpdate.add(item);
            }else {
                yxAppUsageRecordListInsert.add(item);
            }

        }

        // 执行批量操作
        if(yxAppUsageRecordListUpdate.size() > 0){
            yxAppUsageRecordService.updateYxAppUsageRecords(yxAppUsageRecordListUpdate);
        }

        // 执行批量插入
        if(yxAppUsageRecordListInsert.size() > 0){
            yxAppUsageRecordService.insertYxAppUsageRecords(yxAppUsageRecordListInsert);
        }

    }

    public R<String> upLoadAppInfoList(Map<String,String> appInfoVo) {

        if(appInfoVo == null || appInfoVo.size() == 0){
            return R.fail("数据 不能为空");
        }

        List<YxAndroidApplication> yxAndroidApplicationList = yxAndroidApplicationService.selectYxAndroidApplicationByPackageNames(new ArrayList<>(appInfoVo.keySet()));

        for(YxAndroidApplication yxAndroidApplication : yxAndroidApplicationList){
            yxAndroidApplication.setIcon(appInfoVo.get(yxAndroidApplication.getPackageName()));
        }
        yxAndroidApplicationService.updateYxAndroidApplications(yxAndroidApplicationList);

        return R.ok("更新成功");
    }


    public R<Map> appUsageList() {

        //获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();

        //获取当前默认绑定设备
        YxUserAndDevice query = new YxUserAndDevice();
        query.setUserId(user.getUserId());
        query.setIsDefult(DeviceConstants.USER_DEFULT_DEVICE);
        List<YxUserAndDevice> yxUserAndDeviceList= yxUserAndDeviceService.selectYxUserAndDeviceList(query);
        if(yxUserAndDeviceList == null || yxUserAndDeviceList.size() != 1){
            return R.fail("当前用户暂无绑定设备");
        }

        //获取当前默认绑定设备
        YxUserAndDevice queryIndex = new YxUserAndDevice();
        queryIndex.setUserId(user.getUserId());
        List<YxUserAndDevice> yxUserAndDeviceListIndex= yxUserAndDeviceService.selectYxUserAndDeviceList(queryIndex);

        int deviceIndex = 0;
        for(YxUserAndDevice yxUserAndDevice : yxUserAndDeviceListIndex){
            if(yxUserAndDevice.getId().equals(yxUserAndDeviceList.get(0).getId())){
                break;
            }
            deviceIndex++;
        }

        Map<String,Object> returnMap = new HashMap<>();
        // 查询数据
        YxAppUsageRecord query2 = new YxAppUsageRecord();
        query2.setDeviceId(yxUserAndDeviceList.get(0).getDeviceId());
        query2.setUsageDate(DateUtils.getZeroClockTimestampToday());
        List<YxUserAndDeviceVo> list = yxAppUsageRecordService.selectYxAppUsageList(query2);

        returnMap.put("today",list);

        query2.setDeviceId(yxUserAndDeviceList.get(0).getDeviceId());
        query2.setUsageDate(DateUtils.getZeroClockTimestampByDay(-1));
        list = yxAppUsageRecordService.selectYxAppUsageList(query2);
        returnMap.put("yesterday",list);

        // 查询7日数据
        list = yxAppUsageRecordService.selectYxAppUsageWeekList(
                yxUserAndDeviceList.get(0).getDeviceId(),
                DateUtils.getZeroClockTimestampByDay(-7),
                DateUtils.getZeroClockTimestampByDay(0)
                );

        Map<Long,Long> dateTimeMap = new HashMap<>();
        for(YxUserAndDeviceVo vo : list){
            dateTimeMap.put(vo.getUsageDate().getTime(),vo.getUsageTime());
        }

        String format = "MM-dd";
        List<String> categoriesList = new ArrayList<>();
        List<Long> dataList = new ArrayList<>();

        for(int i = -6 ; i <= 0 ; i++){
            Date date = DateUtils.getZeroClockTimestampByDay(i);
            categoriesList.add(DateUtils.parseDateToStr(format,date));
            if(dateTimeMap.containsKey(date.getTime() )){
                long time = 0;
                if(dateTimeMap.get(date.getTime()) < 60000){
                    time = 1;
                }else {
                    time = dateTimeMap.get(date.getTime()) / 60000;
                }
                dataList.add(time);
            }else {

                dataList.add(0l);
            }
        }

        // 组装echart表格格式数据
        Map seriesMap = new HashMap();

        seriesMap.put("data",dataList);
        seriesMap.put("name","使用时长(分钟)");

        Map weekMap = new HashMap();
        weekMap.put("categories",categoriesList);
        weekMap.put("series",Arrays.asList(seriesMap));

        returnMap.put("weekData",weekMap);

        // 增加设备管控状态 查询
        String deviceId = yxUserAndDeviceList.get(0).getDeviceId();
        AndroidDevice androidDevice = new AndroidDevice();
        androidDevice.setDeviceId(deviceId);
        List<AndroidDevice> androidDeviceList = androidDeviceService.selectAndroidDeviceList(androidDevice);

        if(androidDeviceList == null || androidDeviceList.size() != 1){
            return R.fail("设备异常");
        }

        YxDeviceExtraInfo query3 = new YxDeviceExtraInfo();
        query3.setdId(androidDeviceList.get(0).getId());
        List<YxDeviceExtraInfo> list3 = yxDeviceExtraInfoService.selectYxDeviceExtraInfoList(query3);
        if(list3 == null || list3.size() == 0){
            returnMap.put("controlMode",0);
            returnMap.put("stuName","");
            returnMap.put("deviceIndex",deviceIndex);
            returnMap.put("isLockScreen",false);
        }else {
            returnMap.put("controlMode",list3.get(0).getControlMode());
            returnMap.put("stuName",list3.get(0).getStuName());
            returnMap.put("deviceIndex",deviceIndex);
            returnMap.put("isLockScreen",list3.get(0).getIsLockScreen() == null ? 0 : list3.get(0).getIsLockScreen() == 1);
        }


        return R.ok(returnMap);
    }

    public R<List<YxAndroidApplicationVo>> appList() {

        //获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();

        //获取当前默认绑定设备
        YxUserAndDevice query = new YxUserAndDevice();
        query.setUserId(user.getUserId());
        query.setIsDefult(DeviceConstants.USER_DEFULT_DEVICE);
        List<YxUserAndDevice> yxUserAndDeviceList= yxUserAndDeviceService.selectYxUserAndDeviceList(query);
        if(yxUserAndDeviceList == null || yxUserAndDeviceList.size() != 1){
            return R.fail("当前用户暂无绑定设备");
        }

        // 查询数据
        List list = yxAndroidApplicationService.selectYxAndroidApplicationByDeviceId(yxUserAndDeviceList.get(0).getDeviceId());
        return R.ok(list);

    }

    public R<List<YxAndroidApplicationVo>> appAuthorizeList() {

        //获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();

        //获取当前默认绑定设备
        YxUserAndDevice query = new YxUserAndDevice();
        query.setUserId(user.getUserId());
        query.setIsDefult(DeviceConstants.USER_DEFULT_DEVICE);
        List<YxUserAndDevice> yxUserAndDeviceList= yxUserAndDeviceService.selectYxUserAndDeviceList(query);
        if(yxUserAndDeviceList == null || yxUserAndDeviceList.size() != 1){
            return R.fail("当前用户暂无绑定设备");
        }

        // 查询数据
        List list = yxAndroidApplicationService.selectYxAndroidApplicationByDeviceIdAndStatus(yxUserAndDeviceList.get(0).getDeviceId(), (int) AppConstants.APP_STATUS_ENABLE);
        return R.ok(list);

    }

    public R<List<YxAndroidApplicationVo>> deviceAppAuthorizeList() {

        //获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();

        // 查询数据
        List list = yxAndroidApplicationService.selectYxAndroidApplicationByDeviceIdAndStatus(user.getUserName(), (int) AppConstants.APP_STATUS_ENABLE);
        return R.ok(list);

    }

    /**
     * 授权应用
     * @param appList
     * @return
     */
    public R<String> authorizeAppSave(List<YxAndroidApplicationVo> appList) {

        if(appList == null || appList.size() == 0){
            return R.fail("applist 不可为空");
        }

        //获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();

        //获取当前默认绑定设备
        YxUserAndDevice query = new YxUserAndDevice();
        query.setUserId(user.getUserId());
        query.setIsDefult(DeviceConstants.USER_DEFULT_DEVICE);
        List<YxUserAndDevice> yxUserAndDeviceList= yxUserAndDeviceService.selectYxUserAndDeviceList(query);
        if(yxUserAndDeviceList == null || yxUserAndDeviceList.size() != 1){
            return R.fail("当前用户暂无绑定设备");
        }

        List<YxDeviceAndApp> yxDeviceAndAppList = new ArrayList<>();
        for(YxAndroidApplicationVo yxUserAndDeviceVo : appList){
            YxDeviceAndApp yxDeviceAndApp = new YxDeviceAndApp();
            yxDeviceAndApp.setId(yxUserAndDeviceVo.getDaId());
            yxDeviceAndApp.setStatus(AppConstants.APP_STATUS_ENABLE);
            yxDeviceAndAppList.add(yxDeviceAndApp);
        }

        yxDeviceAndAppService.updateYxDeviceAndAppStatus(yxDeviceAndAppList);

        // 通知设备 管控应用变化
        YxDeviceAndGetui yxDeviceAndGetui = new YxDeviceAndGetui();
        yxDeviceAndGetui.setDeviceId(yxUserAndDeviceList.get(0).getDeviceId());
        List<YxDeviceAndGetui> yxDeviceAndGetuiList = yxDeviceAndGetuiService.selectYxDeviceAndGetuiList(yxDeviceAndGetui);
        if(yxDeviceAndGetuiList != null && yxDeviceAndGetuiList.size() == 1){
            AsyncManager.me().execute(AsyncFactory.transmissionPushByCid(yxDeviceAndGetuiList.get(0).getCid(), GTPush.create(GeTuiPushConstants.DEVICE_APP_AUTHORIZE_UPDATE)));
        }

        return R.ok();
    }


}
